/*
 * Copyright (c) 2020-2099 the original author or authors. All rights reserve.
 */
package org.tianyun.cloud.data.redis;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.core.Ordered;
import org.tianyun.cloud.data.redis.autoconfigure.RedisContainerAutoConfiguration;

import java.util.List;

/**
 * 通过@RedisContainer注解来初始化Redis连接，配合RedisContainerRegistrar使用，这一步用来移除springboot自动配置的bean，替换成自己的bean
 *
 * @auther ebert_chan
 */
public class RedisContainerPostProcessor implements BeanDefinitionRegistryPostProcessor, Ordered {

    private List<RedisConnectionFactoryConfigurer> redisConnectionFactoryConfigurer;

    private int order = Ordered.LOWEST_PRECEDENCE - 102;

    public RedisContainerPostProcessor(ObjectProvider<List<RedisConnectionFactoryConfigurer>> redisConnectionFactoryConfigurerProvider) {
        this.redisConnectionFactoryConfigurer = redisConnectionFactoryConfigurerProvider.getIfAvailable();
    }

    /*
     * @see org.springframework.core.Ordered#getOrder()
     */
    @Override
    public int getOrder() {
        return this.order;
    }

    /*
     * @see org.springframework.beans.factory.config.BeanFactoryPostProcessor#postProcessBeanFactory(org.springframework.beans.factory.config.
     * ConfigurableListableBeanFactory)
     */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    }

    /*
     * @see org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry(org.springframework.beans.
     * factory.support.BeanDefinitionRegistry)
     */
    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {

        if (redisConnectionFactoryConfigurer == null || redisConnectionFactoryConfigurer.isEmpty()) {
            return;
        }

        String[] beanNames = RedisContainerAutoConfiguration.REMOVE_BEAN_NAMES;
        for (int i = 0; i < beanNames.length; i++) {
            if (registry.containsBeanDefinition(beanNames[i])) {
                registry.removeBeanDefinition(beanNames[i]);
            }
        }

        redisConnectionFactoryConfigurer.forEach(c -> c.registryBean(registry));

    }

}
